<?php

// +----------------------------------------------------------------------
// | 简易CMS
// +----------------------------------------------------------------------
// | Copyright (C) 2010 Hoping Software Studio.
// +----------------------------------------------------------------------
// | Version $Id$ <http://www.zjzit.cn>
// +----------------------------------------------------------------------
namespace app\admin\controller;

/**
 * 后台配置控制器
 * @author yangweijie <yangweijiester@gmail.com>
 */
class Menu extends AdminController {
    /**
     * 后台菜单首页
     * @return none
     */
    public function index() {
        $pid = I('get.pid', 0);
        if ($pid) {
            $data = D('Menu')->where("id={$pid}")->field(true)->find();
            $this->assign('data', $data);
        }
        $title = trim(I('get.title'));
        $type = C('CONFIG_GROUP_LIST');
        $all_menu = M('Menu')->column('id,title');
        $map['pid'] = $pid;
        if ($title) {
            $map['title'] = array('like', "%{$title}%");
        }
        $list = D("Menu")->where($map)->field(true)->order('sort asc,id asc')->select();
        int_to_string($list, array('hide' => array(1 => '是', 0 => '否'), 'is_dev' => array(1 => '是', 0 => '否')));
        if ($list) {
            foreach ($list as &$key) {
                if ($key['pid']) {
                    $key['up_title'] = $all_menu[$key['pid']];
                }
            }
            $this->assign('list', $list);
        }
        // 记录当前列表页的cookie
        Cookie('__forward__', $_SERVER['REQUEST_URI']);

        $this->meta_title = '菜单列表';
        return $this->fetch();
    }

    /**
     * 新增菜单
     * @author yangweijie <yangweijiester@gmail.com>
     */
    public function add() {
        if (IS_POST) {
            $Menu = D('Menu');
            $data = I('post.');
            if ($data) {
                $id = $Menu->add($data);
                if ($id) {
                    session('ADMIN_MENU_LIST', null);
                    //记录行为
                    action_log('update_menu', 'Menu', $id, UID);
                    $this->success('新增成功', Cookie('__forward__'));
                } else {
                    $this->error('新增失败');
                }
            } else {
                $this->error($Menu->getError());
            }
        } else {
            $this->assign('info', array('pid' => I('pid')));
            $menus = D('Menu')->field(true)->select();
            $tree = new \CMS\Tree();
            $menus = $tree->toFormatTree($menus);
            $menus = array_merge(array(0 => array('id' => 0, 'title_show' => '顶级菜单')), $menus);
            $this->assign('Menus', $menus);
            $this->meta_title = '新增菜单';
            return $this->fetch('edit');
        }
    }

    /**
     * 编辑配置
     * @author yangweijie <yangweijiester@gmail.com>
     */
    public function edit($id = 0) {
        if (IS_POST) {
            $Menu = D('Menu');
            $data = I('post.');
            if ($data) {
                if ($Menu->save($data, array('id' => $data['id'])) !== false) {
                    session('ADMIN_MENU_LIST', null);
                    //记录行为
                    action_log('update_menu', 'Menu', $data['id'], UID);
                    $this->success('更新成功', Cookie('__forward__'));
                } else {
                    $this->error('更新失败');
                }
            } else {
                $this->error($Menu->getError());
            }
        } else {
            $info = array();
            /* 获取数据 */
            $info = D('Menu')->field(true)->find($id);
            $menus = D('Menu')->field(true)->select();
            $tree = new \CMS\Tree();
            $menus = $tree->toFormatTree($menus);

            $menus = array_merge(array(0 => array('id' => 0, 'title_show' => '顶级菜单')), $menus);
            $this->assign('Menus', $menus);
            if (false === $info) {
                $this->error('获取后台菜单信息错误');
            }
            $this->assign('info', $info);
            $this->meta_title = '编辑后台菜单';
            return $this->fetch();
        }
    }

    /**
     * 删除后台菜单
     * @author yangweijie <yangweijiester@gmail.com>
     */
    public function del() {
        $id = array_unique((array) I('id/a', 0));
        if (empty($id)) {
            $this->error('请选择要操作的数据!');
        }
        $map = array('id' => array('in', implode(',', $id)));
        $mModel = D('Menu');
        if ($mModel->where($map)->delete() !== FALSE) {
            session('ADMIN_MENU_LIST', null);
            //记录行为
            action_log('update_menu', 'Menu', $id, UID);
            $this->success('删除成功');
        } else {
            $this->error('删除失败！' . $mModel->getError());
        }
    }

    public function toogleHide($id, $value = 1) {
        session('ADMIN_MENU_LIST', null);
        $this->editRow('Menu', array('hide' => $value), array('id' => $id));
    }

    public function toogleDev($id, $value = 1) {
        session('ADMIN_MENU_LIST', null);
        $this->editRow('Menu', array('is_dev' => $value), array('id' => $id));
    }

    public function importFile($tree = null, $pid = 0) {
        if ($tree == null) {
            $file = APP_PATH . "Admin/Conf/Menu.php";
            $tree = require_once($file);
        }
        $menuModel = D('Menu');
        foreach ($tree as $value) {
            $add_pid = $menuModel->add(
                array(
                    'title' => $value['title'],
                    'url'   => $value['url'],
                    'pid'   => $pid,
                    'hide'  => isset($value['hide']) ? (int) $value['hide'] : 0,
                    'tip'   => isset($value['tip']) ? $value['tip'] : '',
                    'group' => $value['group'],
                )
            );
            if ($value['operator']) {
                $this->import($value['operator'], $add_pid);
            }
        }
    }

    public function import() {
        if (IS_POST) {
            $tree = I('post.tree');
            $lists = explode(PHP_EOL, $tree);
            $menuModel = M('Menu');
            if ($lists == array()) {
                $this->error('请按格式填写批量导入的菜单，至少一个菜单');
            } else {
                $pid = I('post.pid');
                foreach ($lists as $key => $value) {
                    $record = explode('|', $value);
                    if (count($record) == 2) {
                        $menuModel->add(array(
                            'title'  => $record[0],
                            'url'    => $record[1],
                            'pid'    => $pid,
                            'sort'   => 0,
                            'hide'   => 0,
                            'tip'    => '',
                            'is_dev' => 0,
                            'group'  => '',
                        ));
                    }
                }
                session('ADMIN_MENU_LIST', null);
                $this->success('导入成功', U('index?pid=' . $pid));
            }
        } else {
            $this->meta_title = '批量导入后台菜单';
            $pid = (int) I('get.pid');
            $this->assign('pid', $pid);
            $data = M('Menu')->where("id={$pid}")->field(true)->find();
            $this->assign('data', $data);
            return $this->fetch();
        }
    }

    /**
     * 菜单排序
     * @author huajie <banhuajie@163.com>
     */
    public function sort() {
        if (IS_GET) {
            $ids = I('get.ids');
            $pid = I('get.pid');

            //获取排序的数据
            $map = array('status' => array('gt', -1));
            if (!empty($ids)) {
                $map['id'] = array('in', $ids);
            } else {
                if ($pid !== '') {
                    $map['pid'] = $pid;
                }
            }
            $list = M('Menu')->where($map)->field('id,title')->order('sort asc,id asc')->select();

            $this->assign('list', $list);
            $this->meta_title = '菜单排序';
            return $this->fetch();
        } elseif (IS_POST) {
            $ids = I('post.ids');
            $ids = explode(',', $ids);
            foreach ($ids as $key => $value) {
                $res = M('Menu')->where(array('id' => $value))->setField('sort', $key + 1);
            }
            if ($res !== false) {
                session('ADMIN_MENU_LIST', null);
                $this->success('排序成功！');
            } else {
                $this->error('排序失败！');
            }
        } else {
            $this->error('非法请求！');
        }
    }

}
